//
//  STMOrderStatusViewController.m
//  StoreManagement
//
//  Created by centling on 16/5/13.
//  Copyright © 2016年 alfred. All rights reserved.
//

#import "STMOrderStatusViewController.h"
#import "STMOrderManagementTableViewCell.h"
#import "STMRefundAuditView.h"

@interface STMOrderStatusViewController ()<UITableViewDataSource, UITableViewDelegate, refundAuditViewDelegate>

@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) BOOL refreshing;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) STMRefundAuditView *ordeCancelView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, copy) NSString *cancelOrderId;

@end

@implementation STMOrderStatusViewController


-(UIView *)maskView{
    if (!_maskView) {
        _maskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _maskView.backgroundColor=[UIColor blackColor];
        _maskView.alpha=0;
        UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(orderCancelViewDisappear)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.automaticallyAdjustsScrollViewInsets = NO;
    self.refreshing = NO;
    self.page = 1;
    self.mainTableView = [[UITableView alloc] init];
    self.mainTableView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H-108);
    [self.mainTableView registerNib:[UINib nibWithNibName:@"STMOrderManagementTableViewCell" bundle:nil] forCellReuseIdentifier:@"cellID"];
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    self.mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mainTableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.mainTableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.mainTableView.mj_footer.automaticallyChangeAlpha = YES;
    self.mainTableView.mj_footer.automaticallyHidden = NO;
    [self.view addSubview:self.mainTableView];
    [self loadData];
    if ([self.orderType isEqualToString:@"10"]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:nOrderPageRefresh object:nil];
    }
}


- (void)loadData {
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getOrderManagementTrueListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                               orderType:self.orderType
                                              orderCount:@"10"
                                                 success:^(STMOrderManagementListModel *result) {
                                                     [SVProgressHUD dismiss];
                                                     self.refreshing = NO;
                                                     [self.mainTableView.mj_header endRefreshing];
                                                     if ([result.code isEqualToString:@"200"]) {
                                                         self.page = 1;
                                                         self.dataArray = [NSMutableArray arrayWithArray:result.result.datas];
                                                         [self.mainTableView reloadData];
                                                         if (self.dataArray.count < 10) {
                                                             [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                             self.mainTableView.mj_footer.alpha = 1;
                                                         } else {
                                                             [self.mainTableView.mj_footer resetNoMoreData];
                                                             self.mainTableView.mj_footer.alpha = 0;
                                                         }
                                                         
                                                     } else if ([result.code isEqualToString:@"401"]) {
                                                         STMLoginViewController *loginVC = [[STMLoginViewController alloc] init];
                                                         UINavigationController *nav = (UINavigationController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                                                         loginVC.loginVCBlock = ^{
                                                             [nav popViewControllerAnimated:NO];
                                                         };
                                                         [nav presentViewController:loginVC animated:YES completion:nil];
                                                         
                                                     } else {
                                                         [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                     }
                                                 }
                                                 failure:^(NSError *err) {
                                                     self.refreshing = NO;
                                                     [self.mainTableView.mj_header endRefreshing];
                                                     [SVProgressHUD dismiss];
                                                     [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                                 }];
    }
}

//上拉加载更多
- (void)loadMoreData {
    self.page ++;
    if (!self.refreshing) {
        self.refreshing = YES;
        [SVProgressHUD showWithStatus:@"加载中..."];
        [STMNetworkAPI getOrderManagementTrueListWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                                               orderType:self.orderType
                                              orderCount:[NSString stringWithFormat:@"%ld", self.page * 10]
                                                 success:^(STMOrderManagementListModel *result) {
                                                     self.refreshing = NO;
                                                     [self.mainTableView.mj_footer endRefreshing];
                                                     if ([result.code isEqualToString:@"200"]) {
                                                         [SVProgressHUD dismiss];
                                                         NSArray *newArray = result.result.datas;
                                                         if (newArray.count == 0) {
                                                             [self.mainTableView.mj_footer endRefreshingWithNoMoreData];
                                                             self.page --;
                                                             return;
                                                         } else {
                                                             [self.dataArray addObjectsFromArray:newArray];
                                                             NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
                                                             for (NSInteger i = [self.mainTableView numberOfRowsInSection:0]; i <[self.dataArray count]; i++){
                                                                 [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:i
                                                                                                                   inSection:0]];
                                                             }
                                                             [self.mainTableView beginUpdates];
                                                             [self.mainTableView insertRowsAtIndexPaths:arrayWithIndexPaths withRowAnimation:UITableViewRowAnimationNone];
                                                             [self.mainTableView endUpdates];
                                                         }
                                                         
                                                     } else if ([result.code isEqualToString:@"401"]) {
                                                         self.page --;
                                                         [GlobalUtil presentLoginVC];
                                                     } else {
                                                         self.page --;
                                                         [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                                     }
                                                 }
                                                 failure:^(NSError *err) {
                                                     self.page --;
                                                     self.refreshing = NO;
                                                     [self.mainTableView.mj_footer endRefreshing];
                                                     [SVProgressHUD dismiss];
                                                     [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                                                 }];
    }
}


- (void)orderCancelViewDisappear {
    [self.maskView removeFromSuperview];
    self.maskView = nil;
    [self.ordeCancelView removeFromSuperview];
    self.ordeCancelView = nil;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    STMOrderManagementTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID" forIndexPath:indexPath];
    STMOrderManagementListdata *cellData = self.dataArray[indexPath.row];
    cell.changeButtonTitleIndex = self.changeButtonTitleIndex;
    cell.cellData = cellData;
    __weak __typeof(self)weakSelf = self;
    if ([self.changeButtonTitleIndex isEqualToString:@"1"]) {
        cell.orderManagementTableViewCellBlock = ^(NSString *orderId){
            [weakSelf loadData];
        };
    }
    if ([self.changeButtonTitleIndex isEqualToString:@"0"]) {
        cell.orderManagementTableViewCellBlock = ^(NSString *orderId){
            self.cancelOrderId = orderId;
            weakSelf.ordeCancelView = [STMRefundAuditView refundAuditView];
            weakSelf.ordeCancelView.delegate = self;
            weakSelf.ordeCancelView.forOrderCancel = YES;
            [weakSelf.ordeCancelView adjustForOrderCancel];
            weakSelf.ordeCancelView.frame = CGRectMake(20, SCREEN_H/2-100, SCREEN_W-40, 200);
            [[[UIApplication sharedApplication] delegate].window addSubview:weakSelf.ordeCancelView];
            [([UIApplication sharedApplication].delegate).window insertSubview:weakSelf.maskView belowSubview:weakSelf.ordeCancelView];
            weakSelf.maskView.alpha = 0.4;
        };
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 133;
}

#pragma mark -- orderCancelViewDelegate
- (void)agreeOrDisagreeWithState:(NSString *)state Message:(NSString *)message returnType:(NSString *)returnType {
    if ([state isEqualToString:@"3"]) {
        [self orderCancelViewDisappear];
        return;
    }
    [STMNetworkAPI orderCancelWithKey:[UserDefaultHandler getUserDetaultString:kUserKey]
                              orderId:self.cancelOrderId
                               reason:message
                              success:^(STMLoginModel *result) {
                                  [self orderCancelViewDisappear];
                                  if ([result.code isEqualToString:@"200"]) {
                                      [self loadData];
                                  } else if ([result.code isEqualToString:@"401"]) {
                                      [GlobalUtil presentLoginVC];
                                  } else {
                                      [GlobalUtil HUDShowMessage:result.message addedToView:self.view];
                                  }
                              }
                              failure:^(NSError *err) {
                                  [GlobalUtil HUDShowMessage:@"请检查网络连接" addedToView:self.view];
                              }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
